window.setInterval(function() {
	$.get("action.php?mode=checkreminders", function(data) {
		$('.time').html(data);
	});
}, 60000);

document.addEventListener("paste", function(e) {
	const $hiddenFileInput = $("#file");
	if (!$hiddenFileInput) return;

	const clipboardData = e.clipboardData || window.clipboardData;
	if (!clipboardData) return;

	const items = clipboardData.items;
	for (const item of items) {
		if (item.kind === "file") {
			const file = item.getAsFile();
			if (file) {
				if (file.type.startsWith("image/")) {
					const img = new Image();
					img.src = URL.createObjectURL(file);

					const $button = $("#img");
					$button.css({
						"background-image": `url('${img.src}')`,
						"background-size": "cover",
						"background-position": "center",
						"background-repeat": "no-repeat",
					});
				} else {
					$('#img').addClass('buttonred');
				}

				assignFileToInput($hiddenFileInput[0], file);
			}
		}
	}
});

function assignFileToInput(fileInput, file) {
	const fileList = [file];

	Object.defineProperty(fileInput, 'files', {
		value: fileList,
		writable: false,
	});

	const event = new Event("change", {
		bubbles: true
	});
	fileInput.dispatchEvent(event);
}

$(document).on('click', 'a.link', function(event) {
	event.preventDefault(); // Prevent the default link behavior (opening the URL)

	var linkUrl = $(this).attr('href'); // Get the URL from the href attribute

	// Send the URL to the API using AJAX
	$.ajax({
		url: 'action.php', // Replace with your API endpoint
		method: 'POST',
		data: {
			link: linkUrl,
			mode: "openlink"
		},
		success: function(response) {
			console.log('Link sent successfully:', response);
		},
		error: function(xhr, status, error) {
			console.error('Error sending link:', error);
		}
	});
});

$(document).on('click', '.imagemodal', function(event) {
	$(".imagemodal").remove();
});

function sendpost() {
	if ($('.temporary').length > 0) {
		return false;
	}
	
	
	var text = $('textarea#message').val();
	var date = $('input#date').val();
	if($('input#compress').is(':checked')){
		var compress = 'true'
	} else {
		var compress = 'false'
	}
	var chat = $('input#chat').val();
	var editmsg = $('input#editmsg').val();
	var changedDate = $('input#changedDate').val();
	var fileInput = $('input#file')[0].files[0];

	if (!text.trim() && !fileInput) {
		return false;
	}

	if (editmsg == '0') {
		tmpmsg = document.createElement("div");
		tmpmsg.className = "message received temporary";
		$('div.messages').append(tmpmsg);

		tmpbubble = document.createElement("div");
		tmpbubble.className = "bubble tmpbubble";
		$('div.temporary').append(tmpbubble);
		$('div.tmpbubble').html("<img src='assets/spinner.gif' width=20>");
		const messagesDiv = document.querySelector('.messages');

		messagesDiv.scrollTop = messagesDiv.scrollHeight; // Scroll to the bottom

	} else {
		$('div#' + editmsg + '.message').html("<div class='bubble'><img src='assets/spinner.gif' width=20></div>");
	}

	// Use FormData to handle file uploads
	var formData = new FormData();
	formData.append('mode', 'newmessage');
	formData.append('text', text);
	formData.append('editmsg', editmsg);
	formData.append('chat', chat);
	formData.append('date', date);
	formData.append('compress', compress);
	formData.append('changedDate', changedDate);
	if (fileInput) {
		formData.append('file', fileInput);
	}

	// Submit the new message via POST
	$.ajax({
		url: 'action.php',
		type: 'POST',
		data: formData,
		processData: false, // Prevent jQuery from processing the data
		contentType: false, // Prevent jQuery from setting content type
		success: function(response) {
			console.log('Response:', response);

			// Check if the response is "ok"
			if (response.trim() === "ok") {
				// Fetch updated chat data
				$.get("action.php?mode=getmessages&update=true&id=" + chat, function(data) {
					if (editmsg == '0') {
						$('div.chat').html(data); // Update the chat div with the returned content
						const messagesDiv = document.querySelector('.messages');
						messagesDiv.scrollTop = messagesDiv.scrollHeight; // Scroll to the bottom
					} else {
						getmessage(editmsg);
						stopEdit();
					}
				});
			} else {
				console.error("Unexpected response:", response);
				$('div.temporary').remove();
			}
		},
		error: function(xhr, status, error) {
			console.error('Error:', error);
			$('div.temporary').remove();
		}
	});

	// Clear the input field
	$('textarea#message').val("");
	$('input#file').val(null);
	const button = document.getElementById("img");
	button.style.backgroundImage = `none`;
	$('#img').removeClass('buttonred');
	$('#img').removeClass('redborder');
	$('#postoptions').hide()
	$('textarea').removeClass('resized');
	$('.textarea-close').removeClass('visible');
}

$(document).keydown(function(event) {
	if (event.ctrlKey && event.key === "Enter") {
		sendpost();
	}

	if (event.key === "Escape") {
		$(".imagemodal").remove();
		$('textarea').blur();
	}
});

$(document).on('keydown', '#searchtext', function(event) {
	if (event.key === "Enter") {
		search();
	}
});

function search() {
	$('div.contact').removeClass('current');
	var searchquery = $('#searchtext').val();
	$.get("action.php?mode=search&searchquery=" + searchquery, function(data) {
		$('div.chat').html(data);
		setTimeout(() => {
			const messagesDiv = document.querySelector('.messages');
			if (messagesDiv) {
				messagesDiv.scrollTop = messagesDiv.scrollHeight;
			}
		}, 0);
	});
}

function loadmessages(id) {
	$('div.contact').removeClass('current');
	$.get("action.php?mode=getmessages&id=" + id, function(data) {
		$('div#' + id + '.contact').addClass('current');
		$('div.chat').html(data); // Update the chat div with the returned content
		// Ensure scrolling happens after the DOM is updated and rendered
		setTimeout(() => {
			const messagesDiv = document.querySelector('.messages');
			if (messagesDiv) {
				messagesDiv.scrollTop = messagesDiv.scrollHeight;
			}
		}, 0);
	});
}

function getchatprotected() {
	var id = $('input#chat').val();
	var pass = $('input#getchatprotected').val();
	$.get("action.php?mode=getmessages&pass=" + pass + "&id=" + id, function(data) {
		$('div.chat').html(data); // Update the chat div with the returned content
		const messagesDiv = document.querySelector('.messages');
		messagesDiv.scrollTop = messagesDiv.scrollHeight;
	});
	return false;
}

function imageview(id) {
	imview = document.createElement("div");
	imview.className = "imagemodal";
	document.body.appendChild(imview);
	$('img#' + id + '.attachedimage').clone().css("max-height", "90%").css("max-width", "90%").prop("onclick", null).appendTo(".imagemodal");
	closemodal = document.createElement("div");
	closemodal.className = "closemodal";
	$(closemodal).html("Cerrar").appendTo(".imagemodal");
}

$(document).on('mouseover', '.revealControls', function(event) {
	/*$(this).next().removeClass('min');*/
	$(this).next().css('width', '90px');
	$(this).css('visibility', 'hidden');
});

$(document).on('mouseleave', '.bubble, .chat-header, .sidebar', function(event) {
	switch (true) {
		case $(this).hasClass('bubble'):
			$(this).find('.controls').css('width', '0px');
			$(this).find('.revealControls').css('visibility', 'visible');
			break;
		case $(this).hasClass('chat-header'):
			$('.chatmenu').removeClass('revealChatMenu');
			break;
		case $(this).hasClass('sidebar'):
			$('.actionmenu').removeClass('revealActionMenu');
			break;
	}
});


function downloadfile(id) {
	$("#loader").prop("src", "action.php?mode=downloadfile&id=" + id);
}

function deletemsg(id) {
	$('div.message#' + id).remove();
	$.get("action.php?mode=deletemsg&id=" + id, function(data) {});
}

function editmsg(id) {
	$.get("action.php?mode=getmsg&id=" + id, function(data) {
		// Set the textarea value and focus
		$('textarea#message').val(data);
		$('input#editmsg').val(id);
		$('textarea#message').focus();
		//$('textarea#message').keyup();
		$('textarea#message').addClass('flash-red');
		$('.edit-content').html(data);
		$('.edit-info').addClass('rise');
		setTimeout(function() {
			$('textarea#message').removeClass('flash-red');
		}, 500);

	});
}

function stopEdit() {
	$('textarea#message').val("");
	$('input#file').val(null);
	$('input#editmsg').val("0");
	const button = document.getElementById("img");
	button.style.backgroundImage = `none`;
	$('#img').removeClass('buttonred');
	$('#img').removeClass('redborder');
	$('#postoptions').hide()
	$('textarea').removeClass('resized');
	$('.textarea-close').removeClass('visible');
	$('.edit-info').removeClass('rise');
}

function loadPage(url) {
	$.get("action.php?mode=getpage&id=" + url, function(data) {
		$('div.chat').html(data);
	});
}

function editChat(id) {
	$.get("action.php?mode=getpage&chat_id=" + id + "&id=editchat", function(data) {
		$('div.chat').html(data);
	});
}

function pinChat(id) {
	$.get("action.php?mode=pinchat&id=" + id, function(data) {
		$('div.sidebar').html(data);
		setTimeout(() => {
			loadmessages(id)
		}, 0);
	});
}

function unpinChat(id) {
	$.get("action.php?mode=unpinchat&id=" + id, function(data) {
		$('div.sidebar').html(data);
		setTimeout(() => {
			loadmessages(id)
		}, 0);
	});
}

function getString(str, callback) {
	$.get("action.php?mode=getstring&id=" + str, function(data) {
		callback(data);
	});
}

function deleteChat() {
	closeDialog();
	var id = $(".messages").attr("id");
	$.get("action.php?mode=deletechat&id=" + id, function(data) {
		$('div.sidebar').html(data);
		$('div.chat').html(null);
	});
}

function getDialog(dialogText) {
	dialog = document.createElement("div");
	dialog.className = "dialogmodal";
	document.body.appendChild(dialog);
	$.get("action.php?mode=getdialog&text=" + dialogText, function(data) {
		$(dialog).html(data);
	});
}

function closeDialog() {
	$(".dialogmodal").remove();
}

function moveDatabase() {
	$.get("dirchooser.php", function(drive) {
		$.get("action.php?mode=movedatabase&onlyloc=false&path=" + drive, function(data) {
			window.location.replace("index.php?loadpage=appsettings")
		});
	});
}

function moveDatabaseLoc() {
	$.get("dirchooser.php", function(drive) {
		$.get("action.php?mode=movedatabase&onlyloc=true&path=" + drive, function(data) {
			window.location.replace("index.php?loadpage=appsettings")
		});
	});
}

function getmessage(id) {
	$.get("action.php?mode=getmessage&id=" + id, function(data) {
		$('div#' + id + '.message').replaceWith(data);
	});
}

function highlight(id) {
	$.get("action.php?mode=highlight&id=" + id, function(data) {
		setTimeout(() => {
			getmessage(id)
		}, 0);
	});
}

function unhighlight(id) {
	$.get("action.php?mode=unhighlight&id=" + id, function(data) {
		setTimeout(() => {
			getmessage(id)
		}, 0);
	});
}

function pinmessage(id) {
	$(".pinned-message").remove();
	$.get("action.php?mode=pinmessage&id=" + id, function(data) {
		setTimeout(() => {
			getmessage(id)
			$(data).insertAfter(".chat-header");
		}, 0);
	});
}

function unpinmessage(id) {
	$.get("action.php?mode=unpinmessage&id=" + id, function(data) {
		$(".pinned-message").remove();
		setTimeout(() => {
			getmessage(id)
		}, 0);
	});
}

function toggleTodo(id) {
	$.get("action.php?mode=toggleTodo&id=" + id, function(data) {

	});
}

function toggleOptions() {
	$('#postoptions').toggle()
}

function resizeTextarea() {
	$('textarea').toggleClass('resized');
	$('.textarea-close').toggleClass('visible');
}

function toggleActionMenu() {
	$('.actionmenu').toggleClass('revealActionMenu');
}

function toggleChatMenu() {
	$('.chatmenu').toggleClass('revealChatMenu');
}

function closeTextarea() {
	$('textarea').removeClass('resized');
	$('.textarea-close').removeClass('visible');
}

function uploadpreview(e) {
	const file = e.files[0]; // Get the first file selected
	// Check if the file is an image by checking its MIME type
	if (file && file.type.startsWith("image/")) {
		// Create Blob-URL for the File (Blob) object
		const url = (URL || webkit).createObjectURL(file);
		// Set Blob-URL as the image source
		const button = document.getElementById("img");
		button.style.backgroundImage = `url('${url}')`;
		button.style.backgroundSize = "cover"; // Make the image cover the button
		button.style.backgroundPosition = "center"; // Center the image
		button.style.backgroundRepeat = "no-repeat"; // Avoid repeating the image
		$('#img').addClass('redborder');
	} else {
		$('#img').addClass('buttonred');
	}
}

function changedDate() {
	$('input#changedDate').val("true")
}

$(document).on('keyup', 'textarea', function() {
	var len = $('textarea').val().length;
	var textf = $('.resized').length;

	var txt = $('textarea').val();
	var lines = txt.split(/\r|\r\n|\n/);
	var count = lines.length;

	if (len > 150 && textf == 0 || count > 4 && textf == 0) {
		$('textarea').toggleClass('resized')
		$('.textarea-close').toggleClass('visible');
	}

	if (len < 150 && textf == 1 && count < 4 && textf == 1) {
		$('textarea').toggleClass('resized')
		$('.textarea-close').toggleClass('visible');
	}
});

$(document).on('focusout', 'textarea', function() {
	$('textarea').removeClass('resized');
	$('.textarea-close').removeClass('visible');
});
